//
//  SXHTTPEngine.m
//  Demo6_SXHttpEngine
//
//  Created by SXW on 16/3/3.
//  Copyright © 2016年 盛宣伟. All rights reserved.
//

#import "SXHTTPEngine.h"
#import "AFNetworking.h"
//匿名类的扩展
@interface SXHTTPEngine()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation SXHTTPEngine

//获取 单例 对象
+ (instancetype)shareManager{ //最常用的单例创建
    static SXHTTPEngine *httpEngine = nil;
    //GCD 语法
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"只会调用一次");
    //把对象初始化了
        httpEngine = [[SXHTTPEngine alloc] init];
    });
    return httpEngine;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        //初始化 AFNetWorking
        _manager = [AFHTTPSessionManager manager];
        //响应解析器就可不设置，用默认的json
        //消除服务器 返回的数据类型 跟contentType 字段不一致的影响
        NSMutableSet *set = [NSMutableSet setWithSet:_manager.responseSerializer.acceptableContentTypes];
        [set addObject:@"text/html"];
        _manager.responseSerializer.acceptableContentTypes = set;
    }
    return self;
}

/*get 请求的方法*/
- (void)GET:(NSString*)url params:(NSDictionary*)params success:(Success)success failure:(Failure)failure{
    //
    [_manager GET:url parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        //说明数据请求成功
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        if (failure) {
            failure(error);
        }
    }];
}


/*普通的 post 请求的方法*/
- (void)POST:(NSString*)url params:(NSDictionary*)params success:(Success)success failure:(Failure)failure{
    //
    [_manager POST:url parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        //说明数据请求成功
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        if (failure) {
            failure(error);
        }
    }];
}


@end
